package de.grosjohann.android.feuerwehr.notification;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.net.Uri;
import de.grosjohann.android.feuerwehr.MainActivity;
import de.grosjohann.android.feuerwehr.R;
import de.grosjohann.android.feuerwehr.util.PrefsUtil;

public final class Notify {

  public static final int NOTIFICATION_ID = 112;

  private static Notify notify;

  private Notification notification = new Notification();
  private int notifyCounter;

  private Notify() {
    notification.icon = R.drawable.notificon;

    notifyCounter = 0;
  }

  public static Notify getInstance() {
    if (notify == null) {
      notify = new Notify();
    }

    return notify;
  }

  public void add(Context ctx, String ticker) {
    synchronized (this) {
      notifyCounter += 1;

      if (PrefsUtil.getBoolean(ctx, R.string.prefKeyNotification, false)) {

        vibrate(ctx);
        sound(ctx);

        notification.tickerText = ticker;
        if (notifyCounter > 1) {
          notification.number = notifyCounter;
        }

        Intent notificationIntent = new Intent(ctx, MainActivity.class);

        PendingIntent contentIntent =
            PendingIntent.getActivity(ctx, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        notification.when = System.currentTimeMillis();

        notification.setLatestEventInfo(ctx, ctx.getString(R.string.appName), ticker, contentIntent);

        NotificationManager mNotificationManager =
            (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(NOTIFICATION_ID, notification);
      }
    }
  }

  public void clear(Context ctx) {
    notifyCounter = 0;

    NotificationManager mNotificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.cancel(NOTIFICATION_ID);
  }

  private void vibrate(Context ctx) {
    if (PrefsUtil.getBoolean(ctx, R.string.prefKeyVibration, false)) {
      notification.defaults |= Notification.DEFAULT_VIBRATE;
    } else {
      notification.defaults &= ~Notification.DEFAULT_VIBRATE;
    }
  }

  private void sound(Context ctx) {
    String ringtone = PrefsUtil.getString(ctx, R.string.prefKeyRingtone);
    if (ringtone != null && ringtone.length() > 0) {
      notification.sound = Uri.parse(ringtone);
      notification.audioStreamType = AudioManager.STREAM_NOTIFICATION;
    } else {
      notification.sound = null;
      notification.audioStreamType = 0;
    }
  }
}
